var fs = require("fs");
var path = require("path");





var video2image = require('./video2image');

module.exports = function (UC, source, config, ArFor, cache, package) {

    config.video2image = video2image;


    var ImagelocalPath = config.ImagelocalPath;

    var OpenVideoImage = function (req, res, next) {

        var editimage = config.EditImage;

        var OutputPictures = config.OutputPictures;

        var params = req.params;

        var renderimage = function (imgfile) {
            params.imgfile = imgfile;
            OutputPictures(res, params, {
                name: "video"
            });
        };

        params.cache = config.Files.Temp;
        ImagelocalPath(params, function (error, localpath) {

            if (error == null) {
                renderimage(localpath);
                new source({
                    "SQL": "SELECT db.src FROM files AS db WHERE db.id={id}",
                    "type": "row"
                }, {
                    id: params.id
                }, function (db) {
                    if (db && db.src) {
                        var src = db.src;
                        var OriginalFile = path.join(config.Files.FileCache, src);
                        params.cache = config.Files.Temp;
                        params.OriginalFile = OriginalFile;
                        video2image(params, function (error, db) {
                            if (error) {
                                renderimage()
                                return;
                            }
                            params.cache = config.Files.Temp;
                            params.OriginalFile = db.path;

                            if (process.FormName === 'electron') {
                                params.nativeImage = config.nativeImage;
                            }

                            editimage(params, function (error, val) {
                                if (error) {
                                    renderimage()
                                } else {
                                    renderimage(val.path)
                                }
                            })
                        })
                    } else {

                        renderimage()

                    }
                })


            }
        })
    }

    var router = function (req, res, next) {
        var etag = config.getETag(req.path);
        if (req.isConditionalGET()) {
            var _etag = req.getHeader('if-none-match');
            if (_etag == etag) {
                req.notModified()
                return
            }
        };

        res.etag_key = etag;

        OpenVideoImage(req, res, next)
    }
    return router;

}